package com.niit.servlet;

import com.niit.pojo.Machine;
import com.niit.service.MachineService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/machine")
public class MachineServlet extends HttpServlet {
    private MachineService machineService = new MachineService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");
        String keyword = req.getParameter("keyword");

        if ("add".equals(action)) {
            // 跳转到添加页面
            req.getRequestDispatcher("machine.jsp").forward(req, resp);
        } else if ("edit".equals(action)) {
            String idStr = req.getParameter("id");
            if (idStr != null) {
                int id = Integer.parseInt(idStr);
                Machine machine = machineService.findMachineById(id);
                if (machine != null) {
                    req.setAttribute("machine", machine);
                    System.out.println("已设置编辑机器: " + machine.getDomain()); // 添加调试输出
                } else {
                    req.setAttribute("error", "未找到该机器信息");
                }
            } else {
                req.setAttribute("error", "缺少机器ID参数");
            }
            req.getRequestDispatcher("machine.jsp").forward(req, resp);

        } else if ("delete".equals(action)) {
            String idStr = req.getParameter("id");
            if (idStr != null) {
                int id = Integer.parseInt(idStr);
                try {
                    int result = machineService.deleteMachine(id);
                    if (result > 0) {
                        // 成功时直接返回JSON格式的成功标识（而非重定向）
                        resp.setContentType("application/json;charset=UTF-8");
                        resp.getWriter().write("{\"success\":true,\"message\":\"删除成功\"}");
                        return;
                    } else {
                        resp.setContentType("application/json;charset=UTF-8");
                        resp.getWriter().write("{\"success\":false,\"message\":\"删除失败：记录不存在\"}");
                        return;
                    }
                } catch (Exception e) {
                    System.err.println("删除异常：" + e.getMessage());
                    resp.setContentType("application/json;charset=UTF-8");
                    resp.getWriter().write("{\"success\":false,\"message\":\"删除失败：" + e.getMessage() + "\"}");
                    return;
                }
            }
            // ID为空的情况
            resp.setContentType("application/json;charset=UTF-8");
            resp.getWriter().write("{\"success\":false,\"message\":\"删除失败：缺少ID参数\"}");
        }else {
            List<Machine> machines;
            if (keyword != null && !keyword.trim().isEmpty()) {
                // 执行搜索
                machines = machineService.searchMachines(keyword.trim());
                req.setAttribute("searchKeyword", keyword.trim());
            } else {
                // 查询所有机器
                machines = machineService.findMachines();
            }
            req.setAttribute("machines", machines);
            req.getRequestDispatcher("machine.jsp").forward(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String action = req.getParameter("action");

        if ("add".equals(action)) {
            // 处理添加机器请求
            String domain = req.getParameter("domain");
            String ip = req.getParameter("ip");
            String sphinxPath = req.getParameter("sphinxPath");
            String remark = req.getParameter("remark");

            // 数据验证
            if (domain == null || domain.trim().isEmpty() ||
                    ip == null || ip.trim().isEmpty()) {
                req.setAttribute("error", "域名和IP为必填项");
                // 添加失败，返回添加页面
                req.getRequestDispatcher("machine.jsp").forward(req, resp);
                return;
            }

            // 设置创建时间
            java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String createTime = dateFormat.format(new java.util.Date());

            Machine machine = new Machine();
            machine.setDomain(domain);
            machine.setIp(ip);
            machine.setSphinxPath(sphinxPath);
            machine.setRemark(remark);
            machine.setCreateTime(createTime);

            int result = machineService.addMachine(machine);

            if (result > 0) {
                resp.sendRedirect(req.getContextPath() + "/machine");
            } else {
                req.setAttribute("error", "添加机器失败");
                req.getRequestDispatcher("machine.jsp").forward(req, resp);
            }
        } else if ("edit".equals(action)) {
            // 处理编辑机器请求
            String idStr = req.getParameter("id");
            if (idStr == null) {
                resp.sendRedirect(req.getContextPath() + "/machine");
                return;
            }

            int id = Integer.parseInt(idStr);
            String domain = req.getParameter("domain");
            String ip = req.getParameter("ip");
            String sphinxPath = req.getParameter("sphinxPath");
            String remark = req.getParameter("remark");

            // 数据验证
            if (domain == null || domain.trim().isEmpty() ||
                    ip == null || ip.trim().isEmpty()) {
                req.setAttribute("error", "域名和IP为必填项");
                // 编辑失败，返回当前页面并显示错误
                Machine machine = new Machine();
                machine.setId(id);
                machine.setDomain(domain);
                machine.setIp(ip);
                machine.setSphinxPath(sphinxPath);
                machine.setRemark(remark);
                req.setAttribute("machine", machine);
                req.getRequestDispatcher("machine.jsp").forward(req, resp);
                return;
            }

            Machine machine = new Machine();
            machine.setId(id);
            machine.setDomain(domain);
            machine.setIp(ip);
            machine.setSphinxPath(sphinxPath);
            machine.setRemark(remark);

            int result = machineService.updateMachine(machine);

            if (result > 0) {
                resp.sendRedirect(req.getContextPath() + "/machine");
            } else {
                req.setAttribute("error", "更新机器失败");
                req.setAttribute("machine", machine);
                req.getRequestDispatcher("machine.jsp").forward(req, resp);
            }
        }
    }
}